//
//  PDFView+Indicator.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/23.
//

import UIKit
import PDFKit

extension PDFView {
    /// 彻底隐藏所有指示器，包括滚动时的显示
    func permanentlyHideAllIndicators() {
        // 隐藏当前所有指示器
        hideAllIndicators()
        
        // 找到所有相关的UIScrollView并Hook其setContentOffset方法
        hookScrollViews(in: self)
    }
    
    /// 递归查找所有UIScrollView并Hook其滚动方法
    private func hookScrollViews(in view: UIView) {
        if let scrollView = view as? UIScrollView {
            // 确保指示器始终隐藏
            scrollView.showsVerticalScrollIndicator = false
            scrollView.showsHorizontalScrollIndicator = false
            
            // 交换setContentOffset方法，确保滚动时也保持隐藏
            exchangeSetContentOffsetMethod(for: scrollView)
        }
        
        // 递归处理子视图
        for subview in view.subviews {
            hookScrollViews(in: subview)
        }
    }
    
    /// 交换UIScrollView的setContentOffset方法
    private func exchangeSetContentOffsetMethod(for scrollView: UIScrollView) {
        let originalSelector = #selector(setter: UIScrollView.contentOffset)
        let swizzledSelector = #selector(swizzled_setContentOffset(_:))
        
        let originalMethod = class_getInstanceMethod(UIScrollView.self, originalSelector)
        let swizzledMethod = class_getInstanceMethod(UIScrollView.self, swizzledSelector)
        
        if let originalMethod = originalMethod, let swizzledMethod = swizzledMethod {
            // 交换方法实现
            method_exchangeImplementations(originalMethod, swizzledMethod)
        }
    }
    
    /// 替换的setContentOffset方法，确保指示器隐藏
    @objc private func swizzled_setContentOffset(_ offset: CGPoint) {
        // 先调用原始实现
        swizzled_setContentOffset(offset)
    }
    
    /// 隐藏所有指示器（基础方法）
    private func hideAllIndicators() {
        // 隐藏滚动指示器
        if let scrollView = subviews.compactMap({ $0 as? UIScrollView }).first {
            scrollView.showsVerticalScrollIndicator = false
            scrollView.showsHorizontalScrollIndicator = false
        }
        
        // 隐藏页面控制器指示器
        findAndHidePageControl(in: self)
    }
    
    /// 递归查找并隐藏UIPageControl
    private func findAndHidePageControl(in view: UIView) {
        if let pageControl = view as? UIPageControl {
            pageControl.isHidden = true
            return
        }
        
        for subview in view.subviews {
            findAndHidePageControl(in: subview)
        }
    }
}
